package com.newsmanagement.service.impl;

import com.newsmanagement.common.Constants;
import com.newsmanagement.common.Page;
import com.newsmanagement.dao.IEumCategoryServiceDao;
import com.newsmanagement.dao.INewsCategoryServiceDao;
import com.newsmanagement.entity.NewsCategoryEntity;
import com.newsmanagement.entity.ReturnedMessages;
import com.newsmanagement.service.INewsCategoryService;
import com.newsmanagement.util.CheckAndChangeUtil;
import com.newsmanagement.util.EntityMapChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xbr
 * 2017/12/4 16:29
 * 新闻分类管理service实现
 */
@Service
@Transactional
public class NewsCategoryServiceImpl implements INewsCategoryService {


    @Autowired
    private INewsCategoryServiceDao newsCategoryServiceDao;

    @Autowired
    private IEumCategoryServiceDao eumCategoryServiceDao;

    /**
     * （后台）新闻分类列表获取
     * @param jumpPage 跳转页面
     * @param showSize 每页显示的数据条数
     * @return ReturnedMessages
     */@Override
    public ReturnedMessages categoryList(Integer jumpPage ,Integer showSize){

        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        int totalCount = newsCategoryServiceDao.getNewcategoryListCount();

        List<Map<String ,Object>> newsCategoryList =  newsCategoryServiceDao.getNewcategoryList();
        List listTest =  newsCategoryServiceDao.getNewcategoryListTest();
        System.out.println(listTest.toString());

        Page page = new Page(totalCount,jumpPage,showSize);

        newsCategoryList = newsCategoryList.subList(page.getStartPage(),page.getEndPage());

        List list = new ArrayList();
        if (null != newsCategoryList){
            for (int i = 0; i < newsCategoryList.size(); i++) {
                list.add(EntityMapChange.mapToEntity(newsCategoryList.get(i) ,NewsCategoryEntity.class));
            }

            page.setList(list);
            returnedMessages.setData(page);
            return returnedMessages;
        }else{
            returnedMessages.setCode(400);
            returnedMessages.setMessage("未查找到对应信息");
            return returnedMessages;
        }

    }


    /**
     * （后台）根据新闻分类名称添加新闻分类
     * @param categoryName 分类名称
     * @return
     */
    @Override
    public ReturnedMessages addCategory(String categoryName){

        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证新闻分类名称
        if(null == categoryName || categoryName.trim().length() < Constants.INT_ONE ){
            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类名称传递错误：名称为空");

            return returnedMessages;
        }
        categoryName = categoryName.trim();

        /*
         * 根据新闻分类名称获取数据库中的分类信息，
         * 如果存在未删除则不予以添加，也不进行修改
         * 如果存在已删除则不予以添加，进行修改信息
         * 如果不存在则进行添加
         */
        List<Map<String ,Object>> newsCategoryListMap =  newsCategoryServiceDao.getNewcategoryListByName(categoryName);

        if (null != newsCategoryListMap && newsCategoryListMap.size() > Constants.INT_ZERO){
            //存在

            //存在多个，数据库数据错误
            if (newsCategoryListMap.size() > Constants.INT_ONE){
                returnedMessages.setCode(400);
                returnedMessages.setMessage("数据错误：数据库中存在多个相同分类名称");
                return returnedMessages;
            }

            //存在一个，获取对应的用户数据
            NewsCategoryEntity newsCategory = EntityMapChange.mapToEntity(newsCategoryListMap.get(Constants.INT_ZERO) ,NewsCategoryEntity.class);

            if (null != newsCategory && newsCategory.getDeleteFlag() ==Constants.LONG_ZERO ){
                //存在已删除则不予以添加，进行修改信息

                //根据分类名称激活对应的分类信息，并将排序设为最后
                int updateEumNum = newsCategoryServiceDao.updateNewscategoryByCategoryNameForActivation(categoryName);
                if (updateEumNum == Constants.INT_ZERO){
                    returnedMessages.setCode(300);
                    returnedMessages.setMessage("根据分类名称未查找到对应的分类信息");
                }else{
                    // 根据分类名称修改激活的分类信息的排序等级（最后，即当前自增主键的最大值）
                    newsCategoryServiceDao.updateNewscategoryOrderNumberMinusOne(categoryName ,newsCategory.getOrderNumber());

                    returnedMessages.setData(updateEumNum);
                    return returnedMessages;
                }

            }else if (null != newsCategory && newsCategory.getDeleteFlag() == Constants.LONG_ONE){
                //存在未删除则不予以添加，也不进行修改
                returnedMessages.setCode(400);
                returnedMessages.setMessage("分类信息已经存在，请重新选择");
                return returnedMessages;
            }
        }
        //不存在,进行添加
        //添加用户
        int addNum= newsCategoryServiceDao.addNewscategory(categoryName);
        if (addNum < Constants.INT_ONE){
            returnedMessages.setCode(400);
            returnedMessages.setMessage("分类信息保存未成功");
        }

        return returnedMessages;
    }


    /**
     * （后台）根据新闻分类id修改对应的新闻分类信息
     * @param categoryId 新闻分类id
     * @param categoryName 新闻分类名称
     * @return ReturnedMessages
     */
    @Override
    public ReturnedMessages updateCategory(Integer categoryId ,String categoryName){
        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证新闻分类名称
        if(null == categoryName || categoryName.trim().length() < Constants.INT_ONE ){
            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类名称传递错误：名称为空");

            System.out.println(returnedMessages.getMessage());
            return returnedMessages;
        }
        categoryName = categoryName.trim();

        //验证新闻分类id
        if(null == categoryId || categoryId < Constants.INT_ONE ){
            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类id传递错误：id为空");

            System.out.println(returnedMessages.getMessage());
            return returnedMessages;
        }

        //根据新闻分类id修改数据库中的分类信息，
        int updateNumber =  newsCategoryServiceDao.updateNewscategoryNameByCategoryId(categoryId ,categoryName);

        if (updateNumber > Constants.INT_ZERO){//修改成功

            returnedMessages.setData(updateNumber);
        }else {//没有成功修改到数据

            returnedMessages.setCode(400);
            returnedMessages.setMessage("分类信息修改未成功，执行SQL语句无效");
        }

        System.out.println(returnedMessages.getMessage());
        return returnedMessages;
    }


    /**
     * （后台）根据新闻分类id删除对应的新闻分类（逻辑删除）
     * 同时删除掉分类下的新闻内容
     * @param categoryId 分类id
     * @return ReturnedMessages
     */
    @Override
    public ReturnedMessages deleteCategory(Integer categoryId){
        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证新闻分类id
        if(null == categoryId || categoryId < Constants.INT_ONE ){

            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类id传递错误：id为空");

            System.out.println(returnedMessages.getMessage());
        }else {

            //删除分类信息（逻辑删除）
            int deleteNumber = newsCategoryServiceDao.deleteNewscategoryByCategoryId(categoryId);
            if(deleteNumber < Constants.INT_ONE){
                returnedMessages.setCode(400);
                returnedMessages.setMessage("分类信息删除未成功，执行SQL语句无效");
            }
        }

        return returnedMessages;
    }


    /**
     * （后台）根据新闻分类id操作分类的移动
     * 注意：排序数字为越小越前，可能和页面显示的列表不同
     * @param categoryId 分类id
     * @param operating 操作编码：0，跳到最后方;1,前移一级；2，后移一级；3，跳到最前方；默认为0
     * @return ReturnedMessages
     */
    @Override
    public ReturnedMessages moveCatatoryOrder(Integer categoryId ,Integer operating){
        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证新闻分类id
        if(null == categoryId || categoryId < Constants.INT_ONE ){
            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类id传递错误：id为空");
            return returnedMessages;
        }

        //验证操作编码operating
        if(null == operating || operating < Constants.INT_ZERO || operating > Constants.INT_FOUR){//传入值验证

            operating = Constants.INT_ZERO;
        }


        //根据分类id获取对应的分类信息排序
        Map<String ,Object> map = newsCategoryServiceDao.getNewcategoryListById(categoryId);

        NewsCategoryEntity newsCategoryEntity = EntityMapChange.mapToEntity(map ,NewsCategoryEntity.class);

        if (null == newsCategoryEntity){
            returnedMessages.setCode(500);
            returnedMessages.setMessage("根据分类id未查询到对应的分类信息");
        }
        Integer oldOrderNumber = newsCategoryEntity.getOrderNumber();
        String categoryName = newsCategoryEntity.getCategoryName();
        Integer oldCategoryId = newsCategoryEntity.getCategoryId();

        if (null == oldOrderNumber || oldOrderNumber < Constants.INT_ONE){

            returnedMessages.setCode(500);
            returnedMessages.setMessage("新闻分类id查询出来的信息有误");
            return returnedMessages;
        }
        newsCategoryEntity = null;

        //移动操作选择
        //操作编码：0，跳到最后方;1,前移一级；2，后移一级；3，跳到最前方；默认为0
        Integer newOrderNumber = 0;
        Integer newCategoryId = 0;
        switch (operating){

            case Constants.INT_ZERO://0，跳到最后方

                //修改当前主键对应的新闻分类排序
                newsCategoryServiceDao.updateNewscategoryMaxOrderNumberById(categoryId);
                //修改原本在所修改分类之后的排序
                newsCategoryServiceDao.updateNewscategoryOrderNumberMinusOne(categoryName ,oldOrderNumber);
                break;
            case Constants.INT_ONE://1,前移一级,及减一

                //获取上一级数据信息
                map = newsCategoryServiceDao.getNewcategoryPreviousById(oldOrderNumber);
                NewsCategoryEntity newsCategoryPrevious = EntityMapChange.mapToEntity(map ,NewsCategoryEntity.class);

                if (null == newsCategoryPrevious){//前面没有数据了，不操作
                    returnedMessages.setCode(400);
                    returnedMessages.setMessage("当前新闻分类前无数据");
                    break;
                }
                newOrderNumber = newsCategoryPrevious.getOrderNumber();
                newCategoryId = newsCategoryPrevious.getCategoryId();

                if (null == newOrderNumber || newOrderNumber < Constants.INT_ONE){
                    newOrderNumber = Constants.INT_ONE;
                }

                //交换数据
                newsCategoryServiceDao.moveCatatoryUpperOrNext(oldCategoryId ,newOrderNumber);
                newsCategoryServiceDao.moveCatatoryUpperOrNext(newCategoryId ,oldOrderNumber);

                break;
            case Constants.INT_TWO://2，后移一级

                //获取下一级数据信息
                map = newsCategoryServiceDao.getNewcategoryLastOneById(oldOrderNumber);
                NewsCategoryEntity newsCategoryLastOne = EntityMapChange.mapToEntity(map ,NewsCategoryEntity.class);

                if (null == newsCategoryLastOne){//后面没有数据了，不操作
                    returnedMessages.setCode(400);
                    returnedMessages.setMessage("当前新闻分类后无数据");
                    break;
                }
                newOrderNumber = newsCategoryLastOne.getOrderNumber();
                newCategoryId = newsCategoryLastOne.getCategoryId();

                if (null == newOrderNumber || newOrderNumber < Constants.INT_ONE){
                    newOrderNumber = oldOrderNumber + Constants.INT_ONE;
                }

                //交换数据
                newsCategoryServiceDao.moveCatatoryUpperOrNext(oldCategoryId ,newOrderNumber);
                newsCategoryServiceDao.moveCatatoryUpperOrNext(newCategoryId ,oldOrderNumber);

                break;
            case Constants.INT_THREE://3，跳到最前方

                //修改当前主键对应的新闻分类排序
                newsCategoryServiceDao.updateNewscategoryMinOrderNumberById(categoryId);
                //修改原本在所修改分类之前的排序
                newsCategoryServiceDao.updateNewscategoryOrderNumberAddOne(categoryName ,oldOrderNumber);
                break;
            default:

                break;
        }

        return returnedMessages;
    }


    /**
     * （前台）根据新闻分类ids设置喜欢和不喜欢的新闻分类
     * ids以英文逗号隔开
     * @param eumId 用户主键
     * @param categoryLikeIds 喜欢的新闻分类id集
     * @param categoryDislikeIds 不喜欢的新闻分类id集
     * @return ReturnedMessages
     */
    @Override
    public ReturnedMessages setCatatory(Integer eumId ,String categoryLikeIds ,String categoryDislikeIds){

        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //验证喜欢分类和不喜欢分类是否都没有数据，若没有提示选择
        if (!CheckAndChangeUtil.checkStringHaveData(categoryLikeIds) && !CheckAndChangeUtil.checkStringHaveData(categoryDislikeIds)){
            return returnedMessages.ReturnedMessagesFail(400 ,"请选择喜欢或者不喜欢的新闻分类，不能都不选");
        }

        //用于创建时的标记
        int isSuccess = 0;
        StringBuilder createResult = new StringBuilder();

        /*
         * 先处理敢兴趣的新闻分类，在处理不敢兴趣的新闻分类
         */
        //验证敢兴趣的新闻分类id集
        if(!CheckAndChangeUtil.checkStringHaveData(categoryLikeIds)){

            createResult.append("未选择感兴趣的新闻分类。");
        }else {
            //将ids以逗号分隔开
            String[] categoryLikeIdArray = CheckAndChangeUtil.getStringArrayIsDigital(categoryLikeIds.split(","));
            //创建感兴趣的用户和新闻分类关系表数据
            for (int i = 0; i < categoryLikeIdArray.length; i++) {
                //创建数据

                isSuccess = eumCategoryServiceDao.updateEumCategoryLike(eumId ,Integer.valueOf(categoryLikeIdArray[i]) ,Constants.INT_ONE);
                if (isSuccess > Constants.INT_ZERO){
                    continue;
                }
                isSuccess = eumCategoryServiceDao.addEumCategory(eumId ,Integer.valueOf(categoryLikeIdArray[i]) ,Constants.INT_ONE);
                if (isSuccess < Constants.INT_ONE){
                    createResult.append(categoryLikeIdArray[i]).append("未成功创建;");
                }
            }
        }

        //验证不感兴趣的新闻分类id集
        if(!CheckAndChangeUtil.checkStringHaveData(categoryDislikeIds)){

            createResult.append("未选择不感兴趣的新闻分类。");
        }else {
            //将ids以逗号分隔开
            String[] categoryDislikeIdArray = CheckAndChangeUtil.getStringArrayIsDigital(categoryDislikeIds.split(","));
            //创建不感兴趣的用户和新闻分类关系表数据
            for (int i = 0; i < categoryDislikeIdArray.length; i++) {
                //验证是否存在
                isSuccess = eumCategoryServiceDao.updateEumCategoryLike(eumId ,Integer.valueOf(categoryDislikeIdArray[i]) ,Constants.INT_ZERO);
                if (isSuccess > Constants.INT_ZERO){
                    continue;
                }
                //创建数据
                isSuccess = eumCategoryServiceDao.addEumCategory(eumId ,Integer.valueOf(categoryDislikeIdArray[i]) ,Constants.INT_ZERO);
                if (isSuccess < Constants.INT_ONE){
                    createResult.append(categoryDislikeIdArray[i]).append("未成功创建;");
                }
            }
        }

        return returnedMessages;
    }


    /**
     * （前台）查询新闻分类（过滤个人不感兴趣分类）
     * @param eumId 用户主键
     * @param like 是否喜欢：1，喜欢；0，不喜欢;-1,不喜欢不讨厌
     * @return ReturnedMessages
     */
    public ReturnedMessages likeCategoryList(Integer eumId ,Integer like){
        //格式化返回处理结果
        ReturnedMessages returnedMessages = new ReturnedMessages();

        //新闻分类查询，且为非“不喜欢”的：List<Map<String ,Object>>
        returnedMessages.setData(eumCategoryServiceDao.likeCategoryList(eumId ,like));

        return returnedMessages;
    }



}
